import { createRouter, createWebHashHistory } from 'vue-router'
import { checkVersion } from '@/utils/version';
import pinia from "@/stores/store"
import { useUserStore } from "@/stores/user"
const userStore = useUserStore(pinia)
import storage from "@/utils/storage"
import Login from './modules/Login' // 登录
import DataScreen from './modules/DataScreen'
import NoPermission from './modules/NoPermission/NoPermission'
import FontPage from './modules/FontPage'
import IOT from './modules/IOT'
import MonitoringCenter from './modules/MonitoringCenter'
import SystemManage from './modules/SystemManage'
import UserManageCenter from './modules/UserManageCenter'
import WarnCenter from './modules/WarnCenter'
import EventView from './modules/EventView'
import DispatchCenter from './modules/DispatchCenter'
import Operation from './modules/Operation'
import DigitalAnalysis from './modules/DigitalAnalysis'
import VirtualPowerPlant from './modules/VirtualPowerPlant' // 新增虚拟电厂模块

const routes = [
  {
    path: '/',
    component: () => import('@/views/index.vue'),
    meta: { title: '首页' },
    children: [
      FontPage,
      IOT,
      MonitoringCenter,
      SystemManage,
      UserManageCenter,
      WarnCenter,
      EventView,
      DispatchCenter,
      NoPermission,
      Operation,
      DigitalAnalysis,
      VirtualPowerPlant // 新增虚拟电厂路由
    ]
  },
  Login,
  DataScreen,
  // Dashboard
]

const router = createRouter({
  // history: createWebHistory('/ngp-cloud/'),
  history: createWebHashHistory(),
  routes
})

// 权限检查
const checkUserPermission = async (to) => {
  const targetPath = to.fullPath;
  const simplePath = to.path
  const userId = storage.getItem("USER_INFO")
  // 如果用户未登录且不在登录页，直接跳转到登录页
  if (Object.keys(userId || {}).length === 0 && simplePath !== '/login') {
    return 'login'
  }
  // 登录页面直接放行
  if (simplePath === '/login') {
    return true
  }
  return true
}

router.beforeEach(async (to, from, next) => {
  const hasPermission = await checkUserPermission(to);
  if (hasPermission === 'login') {
    next({ path: '/login', replace: true });
  } else {
    next();
  }
});
router.afterEach(() => {
  if (import.meta.env.VITE_APP_TITLE === 'prod') {
    checkVersion();
  }
})

export default router

